# -*- coding: utf-8 -*-\
# -*- coding: utf-8 -*-
import os
import string

# from live_api.tools import a
from utils_datetime import *
from django.conf import settings
from UpLoad import UpLoad

Upload = UpLoad()


# ret = ufile.upload(request, 'imagefile', 'cms_liuhua/glist/background/')
#if ret != None and ret['data'] != None:
#        db_img_path = ret['db_img_path']
def upload(request, fileName, remotedir):
    fileDir = settings.BASE_DIR + '/live_api/static/image/'
    makedir(fileDir)
    ret = {'status': False, 'data': None, 'error': None}
    img = request.FILES.get(fileName)
    # print img
    if img != None:
        todaytime = utils_datetime.todaytime()
        phototime = 'img%s' % todaytime
        photo_last = str(img).split('.')[-1]
        img_name = "%s.%s" % (phototime, photo_last)
        fliePath = os.path.join(fileDir, img_name)
        remotepath = os.path.join(remotedir, img_name)
        db_img_path = os.path.join(remotedir, img_name)
        # print(fliePath)

        '''
        f = open(fliePath, 'wb')       
        try:
            for chunk in img.chunks(chunk_size=1024):
                f.write(chunk)
            Upload.put(remotepath, fliePath)
            remove(fliePath)
            ret['status'] = True
            ret['data'] = fliePath
            ret['remotepath'] = remotepath
            ret['db_img_path'] = db_img_path
        except Exception as e:
            ret['error'] = e
        finally:
            f.close()
            return ret
        '''
        try:
            with open(fliePath, 'wb') as f:
                for chunk in img.chunks(chunk_size=1024):
                    f.write(chunk)
            Upload.put(remotepath, fliePath)
            remove(fliePath)
            ret['status'] = True
            ret['data'] = fliePath
            ret['remotepath'] = remotepath
            ret['db_img_path'] = db_img_path
        except Exception as e:
            ret['error'] = e
        finally:
            return ret

    else:
        ret['error'] = "没有'%s'文件,请上传文件!"%(fileName)
    return ret

# rets = ufile.uploads(request, 'cimagefile', 'cms_liuhua/glist/item/')
'''
db_img_paths = {}
for ret in rets:
    if ret != None and ret['data'] != None:
        db_img_paths[ret['filename']]=ret['db_img_path']
'''
def uploads(request, fileName, remotedir):
    fileDir = settings.BASE_DIR + '/live_api/static/image/'
    makedir(fileDir)
    imgs = request.FILES.getlist(fileName)
    rets = []
    i = 1
    for img in imgs:
        todaytime = utils_datetime.todaytime()
        phototime = 'img%s%s' % (todaytime, i)
        i += 1
        photo_last = str(img.name).split('.')[-1]
        img_name = "%s.%s" % (phototime, photo_last)
        fliePath = os.path.join(fileDir, img_name)
        remotepath = os.path.join(remotedir, img_name)
        db_img_path = os.path.join(remotedir, img_name)
        f = open(fliePath, 'wb')
        ret = {'status': False, 'data': None, 'error': None}

        try:
            with open(fliePath, 'wb') as f:
                for chunk in img.chunks(chunk_size=1024):
                    f.write(chunk)

            Upload.put(remotepath, fliePath)
            remove(fliePath)
            ret['status'] = True
            ret['data'] = fliePath
            ret['filename'] = img.name
            ret['remotepath'] = remotepath
            ret['db_img_path'] = db_img_path
        except Exception as e:
            ret['error'] = e
        rets.append(ret)
    return rets


class a(object):
    def __init__(self, request):
        self.__request = request

    def Information(self):
        def __getattr__(self, item):
            if self.__request.POST.get(item) == None:
                return ""
            return self.__request.POST.get(item)



# if __name__ == '__main__':
#     from live_api import pili
#     from live_api.tools.Output_Helper import *
#     from live_api.tools.constant import *
#     import live_api.tools.utils_file as ufile
#
#     import os
#     import random
#     import time
#     import sys
#     print 'main'
#
#
#
#
#
#     fileDir = 'C:\Image'
#     files = os.listdir(unicode(fileDir,"utf-8"))
#     remotedir = "cms_liuhua/user/"
#     db = DB.getDB()
#     for localimg in files:
#         nichname = localimg.split(".",1)[0]
#
#         localimg = os.path.join(fileDir,localimg)
#
#
#
#         todaytime = utils_datetime.todaytime()
#         phototime = 'img%s' % todaytime
#
#         photo_last = str(localimg).split('.')[-1]
#         phototime = "%s.%s" % (phototime, photo_last)
#
#         remotepath = os.path.join(remotedir, phototime)
#         Upload.put(remotepath, localimg)
#         # info = a.Information()
#         try:
#             id = maxid("user", "id")
#             print id
#             neteas_euser_info = p.createUserId(accid="new_liuhua_%s" % info.id, name=nichname,icon=datais.url_img+remotepath)
#             print neteas_euser_info
#             if neteas_euser_info['code'] == 200:
#                 accid = neteas_euser_info['info']['accid']
#                 token = neteas_euser_info['info']['token']
#                 try:
#                     cdate = int(time.time())
#                     tel_number=''
#                     cpwd = "123456"
#                     gender = 2
#                     ctype = 0
#                     address = ''
#                     img = remotepath
#                     signature = ''
#                     share_code = ''
#                     par1 = ''
#                     par2 = ''
#                     is_used = 1
#                     salt = ''.join(random.sample(string.ascii_letters + string.digits, 6))
#                     nickname = '%s%s' % (salt, info.id)
#                     cname = info.nickname
#                     sql ="insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" %(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used)
#                     db.execute(sql)
#                     print  str(info.id)+" 注册成功!"
#                 except Exception, e:
#
#                     print "数据库操作异常!" + str(e)
#             else:
#
#                 print '1', "使用网易云信异常!" + str(neteas_euser_info)
#         except Exception, e:
#
#             print '2', "使用网易云信异常!" + str(e)
#         print remotepath
#
#     print '完成'

# ''''''*****************原始的************************************************
'''
        try:
            for chunk in img.chunks(chunk_size=1024):
                f.write(chunk)
            Upload.put(remotepath, fliePath)
            remove(fliePath)
            ret['status'] = True
            ret['data'] = fliePath
            ret['filename'] = img.name
            ret['remotepath'] = remotepath
            ret['db_img_path'] = db_img_path
        except Exception as e:
            ret['error'] = e
        finally:
            f.close()
        rets.append(ret)
    return rets
'''
# ************************************************************************************************
def remove(fliePath):
    os.remove(fliePath)


def makedir(fliePath):
    if not os.path.exists(fliePath):
        os.makedirs(fliePath)
